package com.movisol.usagetrackingclient.services;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

public class UsageTrackingService extends Service {

	Timer t;
	int timeElapsed=0;
	boolean paused=false;
	
	 ArrayList<Messenger> mClients = new ArrayList<Messenger>();

	
	public static final int MSG_START_CLIENT_TRACKING=1;
	public static final int MSG_STOP_CLIENT_TRACKING=2;
	public static final int MSG_PAUSE_CLIENT_TRACKING=3;
	public static final int MSG_RESUME_CLIENT_TRACKING=4;
	public static final int MSG_RESET_CLIENT_TRACKING=5;
	public static final int MSG_UPDATED=5;
	
	
	class IncomingHandler extends Handler {

		/* (non-Javadoc)
		 * @see android.os.Handler#handleMessage(android.os.Message)
		 */
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what){
				case  MSG_START_CLIENT_TRACKING:
					
					mClients.add(msg.replyTo);
					
					TimerTask AsyncTracking = new TimerTask() {
						
						@Override
						public void run() {
							
							if (!paused){
								timeElapsed++;
								for (int i=mClients.size()-1; i>=0; i--) {
									try {
										mClients.get(i).send(Message.obtain(null,MSG_UPDATED,timeElapsed, 0));
									} catch (RemoteException e) {
										// TODO Auto-generated catch block
										mClients.remove(i);
									}

									}
								}
							}
							
						};
					
					t=new Timer();
					t.scheduleAtFixedRate(AsyncTracking, 0,1000);
					break;
				case MSG_PAUSE_CLIENT_TRACKING:
					paused=true;
					break;
				case MSG_RESUME_CLIENT_TRACKING:
					paused=false;
					break;
				case MSG_RESET_CLIENT_TRACKING:
					timeElapsed=0;
					break;
				case MSG_STOP_CLIENT_TRACKING:
					mClients.remove(msg.replyTo);
					t.cancel();
					break;
				default:
	                  super.handleMessage(msg);

			}
			
		}
		
	}
	
	final Messenger mMessenger = new Messenger(new IncomingHandler());
	
	@Override
	public IBinder onBind(Intent arg0) {
		
		return mMessenger.getBinder();
	}

}
